package xyz.shenmegui.foodcheckserver.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import xyz.shenmegui.foodcheckserver.annotation.Login;
import xyz.shenmegui.foodcheckserver.http.HttpException;
import xyz.shenmegui.foodcheckserver.utils.JWTUtil;
import xyz.shenmegui.foodcheckserver.utils.ObjectUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTUtil jwtUtil;

    public static final String USER_KEY = "userid";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Login annotation; // 有login 则不验证token
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
        if (ObjectUtil.isNull(annotation)) {
            return true;
        }
        String token = request.getHeader("token");
        if(ObjectUtil.isNull(token) || token.equals("")){
            token = request.getParameter("token");
        }
        if(token.equals("")){
            throw new HttpException("token不能为空", 401);
        }
//        System.out.println("AuthorizationInterceptor--token:" + token);
        Claims claims = jwtUtil.getClaimsToken(token);
        if (claims == null || jwtUtil.isTokenExpired(claims.getExpiration())) {
            throw new HttpException("token失效，请重新登陆", 401);
        }
        request.setAttribute(USER_KEY, Integer.parseInt(claims.getSubject()));
        return true;
    }
}
